import Koa from "koa";
import path from "path";
import JWT from "koa-jwt";
import Cors from "@koa/cors";
import Helmet from "koa-helmet";
import KoaBody from "koa-body";
import statics from "koa-static";
import jsonutil from "koa-json";
import compress from "koa-compress";
import router from "./routers/router";
import config from "./config/index"
import errorHandle from "./common/ErrorHandle"

const app = new Koa();

const isDevMode = process.env.NODE_ENV === "production" ? false : true;

// 定义公共路径, 不需要JWT鉴权
const jwt = JWT({
  secret: config.JWT_SECRET
  })
  .unless({
    path: [
      // 正则表达式
      /^\/public/,
      /\/login/,
      /\/reg/
    ]
});

app.use(
  new KoaBody({
    multipart: true, // 允许上传多个文件
  })
);
app.use(new Cors());
app.use(new Helmet());
app.use(statics(path.join(__dirname, "../public")));
app.use(
  jsonutil({
    pretty: false,
    param: "pretty",
  })
  );
app.use(errorHandle);
app.use(jwt);
app.use(router.routes(), router.allowedMethods());

if (!isDevMode) {
  // 开发模式压缩中间件
  app.use(compress());
}

app.listen(50922, () => {
  console.log("server listen at 50922");
});
